package cc.ufinity.networkdiagnose.manager;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.ProgressDialog;
import android.content.Context;

public class DownLoadManager {

	public static File getFileFromServer(String path, ProgressDialog pd, String localPath, Context ctx) throws Exception{
		String[] ss = path.split("/");
		String name = ss[ss.length - 1]; 
		
		URL url = new URL(path);
		HttpURLConnection conn =  (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		//获取到文件的大小 
		pd.setMax(conn.getContentLength());
		InputStream is = conn.getInputStream();
//		File file = new File(Environment.getExternalStorageDirectory(), name);
		File file0 = new File(localPath);
		if(!file0.exists())
			file0.mkdir();
		File file = new File(localPath+name);
		if(!file.exists())
			file.createNewFile();
	 	FileOutputStream fos = new FileOutputStream(file);
//		FileOutputStream fos = ctx.openFileOutput(name,Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE); 
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] buffer = new byte[1024];
		int len ;
		int total=0;
		while((len =bis.read(buffer)) != -1){
			fos.write(buffer, 0, len);
			total += len;
			//获取当前下载量
			pd.setProgress(total);
		}
		fos.close();
		bis.close(); 
		is.close();
		
		return file;
	}
}
